<template>
  <view class="settlement-container bg-gray-100 pb-75">
    <!-- 顶部导航栏 -->
    <view class="flex items-center border-b-2 border-red-500 bg-white px-5 py-2 pb-4 pt-12">
      <view class="w-16 flex items-center" @click="handleBack">
        <view class="i-mdi-chevron-left text-2xl text-green-500" />
        <text class="text-base text-green-500">
          返回
        </text>
      </view>
      <view class="flex flex-1 justify-center">
        <text class="text-lg font-bold">
          收银台
        </text>
      </view>
      <view class="w-16" />
    </view>

    <!-- 顶部信息卡片 - 改为上下排列 -->
    <view class="px-3 py-2">
      <!-- 买家信息 -->
      <view class="info-card mb-2 rounded-sm bg-white p-3">
        <view class="mb-1 text-base text-gray-500">
          买家
        </view>
        <view class="flex items-center justify-between">
          <text class="text-base text-black font-normal">
            {{ settlementData.buyerName }}
          </text>
          <text v-if="settlementData.buyerPhone" class="text-sm text-gray-500">
            {{ settlementData.buyerPhone }}
          </text>
        </view>
      </view>

      <!-- 收银时间 -->
      <view class="info-card rounded-sm bg-white p-3">
        <view class="flex items-center justify-between">
          <text class="text-base text-gray-500">
            收银时间
          </text>
          <view class="flex items-center" @click="openTimePicker">
            <text class="mr-1 text-sm text-green-500">
              点击选择时间
            </text>
            <view class="i-mdi-calendar-clock text-green-500" />
          </view>
        </view>
        <view class="mt-1 flex items-center justify-between" @click="openTimePicker">
          <text class="text-base text-black font-normal">
            {{ settlementData.time || '请选择收银时间' }}
          </text>
        </view>
      </view>
    </view>

    <!-- 金额信息区域 -->
    <view class="px-3">
      <!-- 应收区块 - 白色卡片 -->
      <view class="rounded-sm bg-white p-3">
        <!-- 应收金额 -->
        <view class="flex items-center justify-between">
          <text class="text-base text-black">
            应收
          </text>
          <text class="text-lg text-black font-medium">
            {{
              settlementData.yingshou
            }}
          </text>
        </view>

        <!-- 优惠/多收选择 - 添加输入框 -->
        <view class="mt-2 flex items-center">
          <view class="flex overflow-hidden rounded-sm">
            <view
              class="cursor-pointer px-3 py-1.5 text-base" :class="[
                settlementData.discountType === 'discount'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-200 text-gray-700',
              ]" @click="toggleDiscountType('discount')"
            >
              优惠
            </view>
            <view
              class="cursor-pointer px-3 py-1.5 text-base" :class="[
                settlementData.discountType === 'more'
                  ? 'bg-green-500 text-white'
                  : 'bg-gray-200 text-gray-700',
              ]" @click="toggleDiscountType('more')"
            >
              多收
            </view>
          </view>
          <view class="flex-1 text-right">
            <input
              v-model="settlementData.adjustAmountStr" type="text"
              class="inline-block min-w-24 border border-gray-200 rounded-sm px-3 py-1.5 text-right" :class="settlementData.discountType === 'discount' ? 'text-red-500' : 'text-green-500'
              " placeholder="0" readonly @focus="setActiveInput('adjust')"
            >
          </view>
        </view>

        <!-- 实收金额 - 改为输入框 -->
        <view class="mt-2 border border-green-500 rounded-sm bg-green-50 p-3">
          <view class="flex items-center justify-between">
            <text class="text-base text-black">
              现金
            </text>
            <input
              v-model="settlementData.cashAmountStr" type="text"
              class="border-none bg-transparent text-right text-lg text-green-500 font-medium outline-none"
              placeholder="0" readonly @focus="setActiveInput('cash')"
            >
          </view>
        </view>

        <!-- 支付方式选择 -->
        <view class="grid grid-cols-5 mt-2 gap-1 rounded-sm bg-gray-50 p-2">
          <!-- 现金支付 -->
          <view class="relative" @click="selectPaymentMethod('cash')">
            <view
              v-if="settlementData.paymentMethod === 'cash'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              1
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                settlementData.paymentMethod === 'cash' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-cash-multiple mb-1 text-xl" :class="[
                    settlementData.paymentMethod === 'cash' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    settlementData.paymentMethod === 'cash' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  现金
                </text>
              </view>
            </view>
          </view>

          <!-- 微信支付 -->
          <view class="relative" @click="selectPaymentMethod('wechat')">
            <view
              v-if="settlementData.paymentMethod === 'wechat'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              2
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                settlementData.paymentMethod === 'wechat' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-wechat mb-1 text-xl" :class="[
                    settlementData.paymentMethod === 'wechat' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    settlementData.paymentMethod === 'wechat' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  微信
                </text>
              </view>
            </view>
          </view>

          <!-- 支付宝 -->
          <view class="relative" @click="selectPaymentMethod('alipay')">
            <view
              v-if="settlementData.paymentMethod === 'alipay'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              3
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                settlementData.paymentMethod === 'alipay' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-alpha-a-circle mb-1 text-xl" :class="[
                    settlementData.paymentMethod === 'alipay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    settlementData.paymentMethod === 'alipay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  支付宝
                </text>
              </view>
            </view>
          </view>

          <!-- 银联 -->
          <view class="relative" @click="selectPaymentMethod('unionpay')">
            <view
              v-if="settlementData.paymentMethod === 'unionpay'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              4
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                settlementData.paymentMethod === 'unionpay' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-credit-card mb-1 text-xl" :class="[
                    settlementData.paymentMethod === 'unionpay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    settlementData.paymentMethod === 'unionpay' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  银联
                </text>
              </view>
            </view>
          </view>

          <!-- 其他 -->
          <view class="relative" @click="selectPaymentMethod('other')">
            <view
              v-if="settlementData.paymentMethod === 'other'"
              class="payment-badge absolute h-5 w-5 flex items-center justify-center rounded-full bg-red-500 text-xs text-white -left-1 -top-1"
            >
              5
            </view>
            <view
              class="border rounded-sm bg-green-50 p-2" :class="[
                settlementData.paymentMethod === 'other' ? 'border-green-200' : 'border-gray-200',
              ]"
            >
              <view class="flex flex-col items-center">
                <view
                  class="i-mdi-dots-horizontal mb-1 text-xl" :class="[
                    settlementData.paymentMethod === 'other' ? 'text-green-500' : 'text-gray-500',
                  ]"
                />
                <text
                  class="text-sm" :class="[
                    settlementData.paymentMethod === 'other' ? 'text-green-500' : 'text-gray-500',
                  ]"
                >
                  其他
                </text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 软键盘固定在底部 -->
    <view class="fixed bottom-0 left-0 right-0 z-10">
      <!-- 使用数字键盘组件 -->
      <NumberKeyboard
        :actual-amount="actualAmount" :debt-amount="debtAmount" @key-press="handleKeyPress"
        @delete="handleDelete" @clear="handleClear" @debt="handleCheckout" @checkout="handleCheckout"
      />
    </view>
    <!-- 使用up-datetime-picker组件 -->
    <up-datetime-picker
      ref="datetimePickerRef" v-model="dateTimeValue" :show="showTimePicker" mode="datetime"
      @confirm="timeConfirm" @cancel="timeCancel"
    />
  </view>
</template>

<script setup lang="ts">
import type { AddOrderDataReq } from '@/api/order/types';
import { computed, onMounted, reactive, ref } from 'vue';

import { addOrderData } from '@/api/order';
import NumberKeyboard from '@/components/number-keyboard/index.vue';

// 定义订单项接口
interface OrderItem {
  goodsName: string;
  specification?: string;
  quantity: number;
  price: number;
  id?: number | string;
  [key: string]: any;
}

// 编辑信息接口
interface EditInfo {
  editUsername: string;
  editUsernameId: string;
}

// 结算数据接口 - 直接映射到API需要的结构
interface SettlementData {
  // 支付金额
  cash_num: number; // 现金支付金额
  wepay_num: number; // 微信支付金额
  alipay_num: number; // 支付宝支付金额
  union_num: number; // 银联支付金额
  other_num: number; // 其他支付金额

  // 金额计算
  heji: number; // 合计金额(应收)
  yingshou: number; // 应收金额
  shishou: number; // 实收金额(计算值)

  // 优惠/多收相关
  input_num: number; // 输入的调整金额
  discount_num: number; // 优惠/多收金额(带正负号)
  discountType: string; // 'discount' 为优惠, 'more' 为多收
  value: number; // 优惠为0，多收为1

  // 买家信息
  buyerName: string;
  buyerPhone: string;

  // 订单信息
  orderCarData: OrderItem[];
  qudancenterToAccountList: OrderItem[];
  order_id: number;
  status: number;

  // 备注信息
  notes: string;

  // 编辑信息
  editInfo: EditInfo;

  // 时间信息
  time: string;

  // UI状态(不提交到API)
  paymentMethod: string; // 当前选择的支付方式
  adjustAmountStr: string; // 优惠/多收输入框的字符串值
  cashAmountStr: string; // 现金输入框的字符串值
}

// 使用reactive创建结算数据对象
const settlementData = reactive<SettlementData>({
  // 支付金额
  cash_num: 1,
  wepay_num: 0,
  alipay_num: 0,
  union_num: 0,
  other_num: 0,

  // 金额计算
  heji: 1,
  yingshou: 1,
  shishou: 1,

  // 优惠/多收相关
  input_num: 0,
  discount_num: 0,
  discountType: 'discount',
  value: 0,

  // 买家信息
  buyerName: '临时客户',
  buyerPhone: '',

  // 订单信息
  orderCarData: [],
  qudancenterToAccountList: [],
  order_id: 0,
  status: 1,

  // 备注
  notes: '',

  // 编辑信息
  editInfo: {
    editUsername: '',
    editUsernameId: '',
  },

  // 时间信息
  time: '',

  // UI状态(不提交到API)
  paymentMethod: 'cash',
  adjustAmountStr: '0',
  cashAmountStr: '1',
});

const activeInput = ref('cash'); // 当前激活的输入框：'adjust' 或 'cash'
const showTime = ref(true); // 默认显示收银时间

// 日期选择器相关变量
const showTimePicker = ref(false);
const dateTimeValue = ref(Date.now());
const datetimePickerRef = ref(null);

// 计算实际应收金额（应收减去优惠或加上多收）
const actualAmount = computed(() => {
  const adjustValue = settlementData.input_num;
  if (settlementData.discountType === 'discount') {
    return settlementData.yingshou - adjustValue;
  }
  else {
    return settlementData.yingshou + adjustValue;
  }
});

// 计算下欠金额
const debtAmount = computed(() => {
  let payAmount = 0;

  // 根据支付方式获取相应的金额
  switch (settlementData.paymentMethod) {
    case 'cash':
      payAmount = settlementData.cash_num;
      break;
    case 'wechat':
      payAmount = settlementData.wepay_num;
      break;
    case 'alipay':
      payAmount = settlementData.alipay_num;
      break;
    case 'unionpay':
      payAmount = settlementData.union_num;
      break;
    case 'other':
      payAmount = settlementData.other_num;
      break;
  }

  return Math.max(0, actualAmount.value - payAmount);
});

// 更新当前支付方式的金额
const updatePaymentAmount = (amount: number) => {
  switch (settlementData.paymentMethod) {
    case 'cash':
      settlementData.cash_num = amount;
      break;
    case 'wechat':
      settlementData.wepay_num = amount;
      break;
    case 'alipay':
      settlementData.alipay_num = amount;
      break;
    case 'unionpay':
      settlementData.union_num = amount;
      break;
    case 'other':
      settlementData.other_num = amount;
      break;
  }
};

// 同步调整金额到对象
const syncAdjustAmount = () => {
  const inputNum = Number.parseFloat(settlementData.adjustAmountStr) || 0;
  settlementData.input_num = inputNum;

  // 设置优惠/多收标识和金额
  settlementData.value = settlementData.discountType === 'discount' ? 0 : 1;
  settlementData.discount_num = settlementData.discountType === 'discount'
    ? -inputNum
    : inputNum;

  // 更新实收金额
  settlementData.shishou = actualAmount.value;
};

// 同步现金金额到对象
const syncCashAmount = () => {
  const amount = Number.parseFloat(settlementData.cashAmountStr) || 0;
  updatePaymentAmount(amount);
};

// 格式化当前时间
const formatTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 初始化时间相关数据
const initTimeData = () => {
  // 设置当前时间
  settlementData.time = formatTime();

  // 初始化日期时间选择器的值
  dateTimeValue.value = Date.now();
};

// 从本地存储加载结算数据
const loadSettlementData = () => {
  try {
    // 从本地存储获取结算数据
    const storedData = uni.getStorageSync('settlementData');

    if (storedData) {
      // 设置订单相关信息
      settlementData.order_id = storedData.orderId || 0;
      settlementData.buyerName = storedData.buyerName || '临时客户';
      settlementData.buyerPhone = storedData.buyerPhone || '';

      // 设置商品列表
      if (storedData.orderItems && Array.isArray(storedData.orderItems)) {
        settlementData.qudancenterToAccountList = storedData.orderItems;
        settlementData.editInfo.editUsername = storedData.orderItems[0].maijia;
        settlementData.editInfo.editUsernameId = storedData.orderItems[0].maijia_id;
        console.log(settlementData);
      }

      // 设置金额相关信息
      if (storedData.yingshou !== undefined) {
        settlementData.yingshou = Number.parseFloat(storedData.yingshou) || 0;
        settlementData.heji = settlementData.yingshou;
        // 默认设置现金金额为应收金额
        settlementData.cash_num = settlementData.yingshou;
        settlementData.cashAmountStr = settlementData.yingshou.toString();
      }

      // 如果有预设的现金金额，使用预设值
      if (storedData.cash_num !== undefined) {
        settlementData.cash_num = Number.parseFloat(storedData.cash_num) || 0;
        settlementData.cashAmountStr = storedData.cash_num.toString();
      }

      // 如果有优惠金额，设置优惠
      if (storedData.discount !== undefined) {
        settlementData.adjustAmountStr = storedData.discount.toString();
        settlementData.input_num = Number.parseFloat(storedData.discount) || 0;
        settlementData.discountType = 'discount';
        settlementData.value = 0;
        settlementData.discount_num = -(Number.parseFloat(storedData.discount) || 0);
      }

      // 更新实收金额
      settlementData.shishou = actualAmount.value;

      // 读取完后清除本地存储（可选）
      uni.removeStorageSync('settlementData');
    }
    else {
      console.error('本地存储中未找到结算数据');
    }
  }
  catch (error) {
    console.error('获取结算数据失败:', error);
    uni.showToast({
      title: '获取订单数据失败',
      icon: 'none',
    });
  }
};

// 在页面加载时获取传递过来的参数
onMounted(() => {
  initTimeData();
  loadSettlementData();
});

// 切换优惠/多收选择
const toggleDiscountType = (type: string) => {
  settlementData.discountType = type;
  syncAdjustAmount(); // 重新计算相关值
};

// 设置当前激活的输入框
const setActiveInput = (inputType: string) => {
  activeInput.value = inputType;
};

// 处理返回按钮点击
const handleBack = () => {
  uni.navigateBack({
    delta: 1,
  });
};

// 处理数字键盘按键
const handleKeyPress = (key: string) => {
  if (activeInput.value === 'adjust') {
    // 处理优惠/多收输入
    if (settlementData.adjustAmountStr === '0' && key !== '.') {
      settlementData.adjustAmountStr = key;
    }
    else {
      // 检查是否已经有小数点
      if (key === '.' && settlementData.adjustAmountStr.includes('.')) {
        return;
      }
      // 最多两位小数
      if (
        settlementData.adjustAmountStr.includes('.')
        && settlementData.adjustAmountStr.split('.')[1].length >= 2
        && key !== '.'
      ) {
        return;
      }
      settlementData.adjustAmountStr += key;
    }
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    // 处理现金输入
    if (settlementData.cashAmountStr === '0' || (settlementData.cashAmountStr === '1' && key !== '.')) {
      settlementData.cashAmountStr = key;
    }
    else {
      // 检查是否已经有小数点
      if (key === '.' && settlementData.cashAmountStr.includes('.')) {
        return;
      }
      // 最多两位小数
      if (
        settlementData.cashAmountStr.includes('.')
        && settlementData.cashAmountStr.split('.')[1].length >= 2
        && key !== '.'
      ) {
        return;
      }
      settlementData.cashAmountStr += key;
    }
    syncCashAmount();
  }
};

// 处理删除键
const handleDelete = () => {
  if (activeInput.value === 'adjust') {
    if (settlementData.adjustAmountStr.length > 1) {
      settlementData.adjustAmountStr = settlementData.adjustAmountStr.slice(0, -1);
    }
    else {
      settlementData.adjustAmountStr = '0';
    }
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    if (settlementData.cashAmountStr.length > 1) {
      settlementData.cashAmountStr = settlementData.cashAmountStr.slice(0, -1);
    }
    else {
      settlementData.cashAmountStr = '0';
    }
    syncCashAmount();
  }
};

// 处理清除键
const handleClear = () => {
  if (activeInput.value === 'adjust') {
    settlementData.adjustAmountStr = '0';
    syncAdjustAmount();
  }
  else if (activeInput.value === 'cash') {
    settlementData.cashAmountStr = '0';
    syncCashAmount();
  }
};

// 选择支付方式
const selectPaymentMethod = (method: string) => {
  settlementData.paymentMethod = method;

  // 如果切换到非现金支付方式，默认设置支付金额等于实际应收金额
  if (method !== 'cash') {
    updatePaymentAmount(actualAmount.value);
    settlementData.cashAmountStr = actualAmount.value.toString();
  }
  else {
    // 如果是现金，显示已设置的现金金额
    settlementData.cashAmountStr = settlementData.cash_num.toString();
    activeInput.value = 'cash';
  }
};

// 处理收银按钮
const handleCheckout = async (status: number) => {
  // 收银逻辑，这里可以调用API等
  if (settlementData.shishou <= 0) {
    uni.showToast({
      title: '实收金额必须大于0',
      icon: 'none',
    });
    return;
  }

  // 更新状态和实收金额
  settlementData.status = status;
  settlementData.shishou = actualAmount.value;

  // 这里可以添加提交订单的逻辑
  uni.showLoading({
    title: '处理中...',
  });
  console.log(settlementData);

  // 使用类型断言将数据转换为API所需格式
  const orderData: AddOrderDataReq = {
    ...settlementData,
    discount_num: settlementData.discount_num.toString(),
    input_num: settlementData.input_num.toString(),
    order_id: settlementData.order_id.toString(),
    qudancenterToAccountList: settlementData.qudancenterToAccountList as any,
    editInfo: {
      ...settlementData.editInfo,
      editUsernameId: Number(settlementData.editInfo.editUsernameId),
    },
  } as unknown as AddOrderDataReq;

  const res = await addOrderData(orderData);
  console.log(res);
  uni.showToast({
    title: '收银成功',
    icon: 'success',
    duration: 2000,
    success: () => {
      // 延迟返回上一页
      setTimeout(() => {
        uni.navigateBack({
          delta: 1,
        });
      }, 2000);
    },
  });
};

// 打开日期时间选择器
const openTimePicker = () => {
  showTimePicker.value = true;
};

// 确认选择日期时间方法
const timeConfirm = () => {
  try {
    // 将时间戳格式化为YYYY-MM-DD HH:mm格式
    const date = new Date(dateTimeValue.value);
    if (isNaN(date.getTime())) {
      throw new TypeError('无效的日期');
    }

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');

    // 更新显示的时间
    settlementData.time = `${year}-${month}-${day} ${hours}:${minutes}`;

    uni.showToast({
      title: '时间设置成功',
      icon: 'success',
    });
    showTimePicker.value = false;
  }
  catch (error) {
    console.error('日期格式化错误:', error);
    uni.showToast({
      title: '日期格式错误',
      icon: 'none',
    });
  }
};

// 取消选择
const timeCancel = () => {
  showTimePicker.value = false;
};
</script>

<style lang="scss">
.settlement-container {
  width: 100%;
}

.key-btn {
  user-select: none;
}

input {
  outline: none;
}
</style>
